package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.mine.entity.BindingBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.BindingPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.BindingViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.MD5Utils;
import com.beiing.tianshuai.tianshuai.util.RegexUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.netease.nim.uikit.common.util.log.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.MessageFormat;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import okhttp3.ResponseBody;

public class BindingActivity extends BaseActivity implements BindingViewImpl {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.edit_bind_username)
    EditText mEditBindUsername;
    @BindView(R.id.edit_safe_code)
    EditText mEditSafeCode;
    @BindView(R.id.btn_get_safe_code)
    TextView mBtnGetSafeCode;
    @BindView(R.id.edit_bind_password)
    EditText mEditBindPassword;
    @BindView(R.id.cb_agree_warning)
    CheckBox mCbAgreeWarning;
    @BindView(R.id.txt_agree_warning)
    TextView mTxtAgreeWarning;
    @BindView(R.id.btn_bind)
    TextView mBtnBind;

    private static final String TAG = "BindingActivity";
    private Context mContext;
    private BindingPresenter mPresenter;
    private TimeCount mCountDown;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_binding;
    }

    @Override
    protected void init() {
        mContext = this;
        initPresenter();
        initListener();
    }

    private void initPresenter() {
        mPresenter = new BindingPresenter(this);
    }

    private void initListener() {
        // 返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 获取验证码
        mBtnGetSafeCode.setOnClickListener(new BGAOnNoDoubleClickListener() {

            private String mNumber;

            @Override
            public void onNoDoubleClick(View v) {
                mBtnGetSafeCode.setClickable(false);
                mNumber = mEditBindUsername.getText().toString();
                if (RegexUtils.checkMobile(mNumber)) {
                    mPresenter.isAlreadySignUp(mNumber);
                } else {
                    showShortText("手机号格式不正确");
                    mBtnGetSafeCode.setClickable(true);
                }
            }
        });

        // 绑定
        mBtnBind.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mBtnBind.setEnabled(false);
                if (TextUtils.isEmpty(mEditBindUsername.getText())) {
                    showShortText("请输入账号");
                    return;
                }
                if (TextUtils.isEmpty(mEditSafeCode.getText())) {
                    showShortText("请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(mEditBindPassword.getText())) {
                    showShortText("请输入密码");
                    return;
                }
                Intent intent = getIntent();
                String platform = intent.getStringExtra("platform");
                String unionId = intent.getStringExtra("unionId");
                String nickName = intent.getStringExtra("nickName");
                String avatarUrl = intent.getStringExtra("avatarUrl");
                String sign = "";
                String username = mEditBindUsername.getText().toString();
                String code = mEditSafeCode.getText().toString();
                String pass = MD5Utils.getMd5Value(mEditBindPassword.getText().toString());
                mPresenter.submitUserInfo(platform, unionId, nickName, avatarUrl, sign, username, code, pass);

            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mCountDown != null) {
            mCountDown.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在努力加载，请稍后...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(ResponseBody bean) {
        try {
            String result = bean.string();
            JSONObject obj = new JSONObject(result);
            switch (obj.getInt("code")){
                case 200:
                    //请重新登录
                    showShortText("绑定成功");
                    Intent intent=getIntent();
                    //返回结果码
                    setResult(AppConstant.RESULT_BUNDLE_SUCCESS,intent);
//                    Intent intent = new Intent(mContext, LoginActivity.class);
//                    Bundle bundle=new Bundle();
//                    bundle.putBoolean("isQQBinding",true);
//                    intent.putExtras(bundle);
                    //startActivity(intent);
                    finish();
                    break;
                case 400:
                    showShortText("手机号码格式不正确");
                    break;
                case 405:
                    showShortText("验证码错误");
                    break;
                case 402:
                    showShortText("验证码过期");
                    break;
                    default:
                        break;
            }

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        } finally {
            if (mBtnBind != null) {
                mBtnBind.setEnabled(true);
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        showShortText("网络异常");
        mBtnBind.setEnabled(true);
        mBtnGetSafeCode.setClickable(true);
    }

    @Override
    public void getSafeCodeResult(CommonBean bean) {
        LogUtils.i(bean.getCode() + "\n" + bean.getData().getNumber(), TAG);
        if (bean.getCode() == 401) {
            showShortText("请求频繁，请稍后再试。");
            mBtnGetSafeCode.setClickable(true);
        } else {
            showShortText("获取成功");
            mCountDown = new TimeCount(60000, 1000);
            mCountDown.start();
        }
    }

    @Override
    public void isAlreadySignUp(CommonBean bean) {
        int code = bean.getCode();
        String number = mEditBindUsername.getText().toString();
        switch (code) {
            case 200:
                mPresenter.getSignUpCode(number);
                break;
            case 400:
//                showShortText("用户不存在");
                mPresenter.getSignUpCode(number);
                break;
                default:break;
        }
    }

    /**
     * 绑定手机号
     * @param bean 绑定bean
     */
    @Override
    public void bindingSuccess(BindingBean bean) {
        int code=bean.getCode();
        switch (code) {
            case 200:
                //请重新登录
                showShortText("绑定成功");
                //绑定成功，返回用户名和密码
                Intent intent = getIntent();
                intent.putExtra("tel",bean.getData().getTel());
                intent.putExtra("pass",bean.getData().getPass());
                //返回结果码
                setResult(AppConstant.RESULT_BUNDLE_SUCCESS, intent);
//                    Intent intent = new Intent(mContext, LoginActivity.class);
//                    Bundle bundle=new Bundle();
//                    bundle.putBoolean("isQQBinding",true);
//                    intent.putExtras(bundle);
                //startActivity(intent);

                finish();
                break;
            case 400:
                showShortText("手机号码格式不正确");
                break;
            case 405:
                showShortText("验证码错误");
                break;
            case 402:
                showShortText("验证码过期");
                break;
            default:
                break;
        }
    }

    @Override
    public void bindingError(Throwable throwable) {

    }

    /**
     * 获取验证码计时器
     */
    private class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mBtnGetSafeCode.setText("重新获取");
            mBtnGetSafeCode.setTextColor(ContextCompat.getColor(mContext, R.color.text_login_main_color));
            mBtnGetSafeCode.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnGetSafeCode.setClickable(false);
            long l = millisUntilFinished / 1000;
            mBtnGetSafeCode.setText(MessageFormat.format("{0}秒", String.valueOf(l)));
            mBtnGetSafeCode.setTextColor(ContextCompat.getColor(mContext, R.color.text_login_main_color));
        }
    }
}
